define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {
    var start_time_change = false;
    var end_time_change = false;
    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'work/work_template_time/index' + location.search,
                    add_url: 'work/work_template_time/add',
                    edit_url: 'work/work_template_time/edit',
                    del_url: 'work/work_template_time/del',
                    multi_url: 'work/work_template_time/multi',
                    import_url: 'work/work_template_time/import',
                    table: 'work_template_time',
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                fixedColumns: true,
                fixedRightNumber: 1,
                visible: false,
                showToggle: false,
                showColumns: false,
                search:false,
                showExport: false,
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id')},
                        {field: 'name', title: __('Name'), operate: 'LIKE'},
                        {field: 'start_time', title: __('Start_time'),datetimeFormat:'YYYY-MM-DD', operate:false, addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime},
                        {field: 'end_time', title: __('End_time'),datetimeFormat:'YYYY-MM-DD', operate:false, addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime},
                        {field: 'create_time', title: __('Create_time'), operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime},
                        {field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate}
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        add: function () {
            Controller.api.bindevent();
        },
        edit: function () {
            Controller.api.bindevent();
        },
        api: {
            bindevent: function () {

                $("#c-start_time").on("dp.change", function(){
                    console.log(start_time_change);
                    if(start_time_change){
                        $('#tableContainer').empty();                                                                                                                                                                                               $('#tableContainer').empty();
                    }
                });

                $("#c-end_time").on("dp.change", function(){
                    if(end_time_change){
                        $('#tableContainer').empty();
                    }
                });

                $('#c-week_str').change(function() {
                    $('#tableContainer').empty(); // 清空表格内容
                });

                $('#c-grade_group_arr').change(function() {
                    $('#tableContainer').empty(); // 清空表格内容
                });

                $('#generateTable').click(function() {
                    // 获取用户选择的开始时间、结束时间和星期
                    var startTime = $('#c-start_time').val();
                    var endTime = $('#c-end_time').val();
                    var selectedWeekdays = $('#c-week_str').val();
                    var selectedGradeGroupArr = $('#c-grade_group_arr').val();
                    if(!startTime || !endTime || !selectedWeekdays || !selectedGradeGroupArr){
                        layer.msg('请先选择开始时间/结束时间/星期/年级组', {icon: 2});
                        return;
                    }
                    // 清空之前的表格内容
                    $('#tableContainer').empty();

                    // 生成表格
                    var tableHtml = '<table class="table table-bordered">';
                    // 表头
                    tableHtml += '<thead><tr>';
                    tableHtml += '<th>日期</th>';
                    tableHtml += '<th>状态</th>';
                    tableHtml += '</tr></thead>';

                    // 表格内容
                    tableHtml += '<tbody>';
                    var currentDate = new Date(startTime);
                    var endDate = new Date(endTime);

                    while (currentDate <= endDate) {
                        // 检查是否在选择的星期中
                        if (selectedWeekdays.includes(currentDate.getDay().toString())) {
                            tableHtml += '<tr>';
                            tableHtml += '<td>' + formatDate(currentDate) + '</td>';
                            tableHtml += '<td style="text-align: center;">' +
                                '<input id="c-switch-' + formatDate(currentDate) + '" name="row[switch]" type="hidden" value="1">' +
                                '<a href="javascript:;" data-toggle="switcher" class="btn-switcher" data-input-id="c-switch-' + formatDate(currentDate) + '" data-yes="1" data-no="0" >' +
                                '<i class="fa fa-toggle-on text-success fa-2x"></i>' +
                                '</a></td>';
                            tableHtml += '</tr>';
                        }
                        // 增加一天
                        currentDate.setDate(currentDate.getDate() + 1);
                    }
                    tableHtml += '</tbody>';
                    tableHtml += '</table>';
                    $('#tableContainer').html(tableHtml);
                });

                setTimeout(function() {
                    start_time_change = end_time_change = true;
                }, 1000);

                // 格式化日期为 YYYY-MM-DD 格式
                function formatDate(date) {
                    var year = date.getFullYear();
                    var month = (date.getMonth() + 1).toString().padStart(2, '0');
                    var day = date.getDate().toString().padStart(2, '0');
                    return year + '-' + month + '-' + day;
                }

                // 禁止选择相同tr内的下拉选项
                // $('#tableContainer').on('click', '.btn-switcher', function() {
                //     var tr = $(this).closest('tr'); // 获取按钮所在的tr元素
                //     var select = tr.find('select'); // 在tr内查找对应的select元素
                //     var isDisabled = $('#' + $(this).data('input-id')).val() === '1';
                //     select.prop('disabled', isDisabled);
                //     // 如果禁止选择，则禁用所在tr内的年级选择器
                //     if (isDisabled) {
                //         var gradeSelect = tr.find('.form-control[name="row[group]"]');
                //         gradeSelect.prop('disabled', true);
                //         gradeSelect.val("0"); // 设置为请选择
                //     }
                // });

                Form.api.bindevent($("form[role=form]"), null, null, function () {
                    var tableData = [];
                    var errorMessage = ''; // 存储错误消息

                    $('#tableContainer').find('tbody tr').each(function () {
                        var row = {};
                        row.select_time = $(this).find('td:eq(0)').text();
                        row.status = $(this).find('input[name="row[switch]"]').val();
                        // row.grade_group = $(this).find('select[name="row[group]"]').val();
                        tableData.push(row);
                        // if (row.status == 1 && row.grade_group == 0) {
                        //     errorMessage += row.select_time + '未选择年级组</br>';
                        // }
                    });
                    var startTime = $('#c-start_time').val();
                    var endTime = $('#c-end_time').val();

                    if(endTime < startTime){
                        layer.msg('结束时间不能低于开始时间', {icon: 2});
                        return false;
                    }
                    if (tableData.length === 0) {
                        // 数组为空，显示错误消息并阻止表单提交
                        layer.msg('请先生成并选择表格数据', {icon: 2});
                        return false;
                    }

                    if (errorMessage !== '') {
                        layer.msg(errorMessage, {icon: 2});
                        return false; // 阻止表单提交
                    }
                    time_change = true;
                    $('#tableData').val(JSON.stringify(tableData));
                });
            }
        }
    };
    return Controller;
});
